package com.ilxqx.framework.system.service.impl;

import com.ilxqx.framework.system.exception.SystemException;
import com.ilxqx.framework.system.po.ItemEntry;
import com.ilxqx.framework.system.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.List;

/**
 * 发送邮件实现服务类
 * @author venus
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String from;
    private final JavaMailSender mailSender;

    @Autowired
    public MailServiceImpl(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * 发送简单的邮件
     *
     * @param to      收件人
     * @param subject 邮件题目（主题）
     * @param content 邮件内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(content);
        simpleMailMessage.setFrom(this.from);
        mailSender.send(simpleMailMessage);
        log.info("给[{}]的邮件[{}]发送成功", to, subject);
    }

    /**
     * 发送给多个人同一份邮件
     *
     * @param to      收件人列表
     * @param subject 邮件题目
     * @param content 邮件内容
     */
    @Override
    public void sendSimpleMail(List<String> to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to.toArray(String[]::new));
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(this.from);
        mailSender.send(message);
        log.info("给[{}]的邮件[{}]发送成功", Arrays.toString(to.toArray()), subject);
    }

    /**
     * 发送html邮件
     *
     * @param to      收件人
     * @param subject 邮件题目
     * @param content 邮件内容
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送html邮件时产生错误：{}", e);
            throw new SystemException("发送HTML邮件失败");
        }
        log.info("给[{}]的邮件[{}]发送成功", to, subject);
    }

    /**
     * 发送html邮件给多个人
     *
     * @param to      收件人列表
     * @param subject 邮件题目
     * @param content 邮件内容
     */
    @Override
    public void sendHtmlMail(List<String> to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to.toArray(String[]::new));
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送html邮件时产生错误：{}", e);
            throw new SystemException("发送HTML邮件失败");
        }
        log.info("给[{}]的邮件[{}]发送成功", Arrays.toString(to.toArray()), subject);
    }

    /**
     * 发送带附件的邮件
     *
     * @param to      收件人
     * @param subject 邮件题目
     * @param content 邮件内容（html）
     * @param files   邮件附件（一个或多个）
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, List<String> files) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            for (String file : files) {
                FileSystemResource fileSystemResource = new FileSystemResource(file);
                if (fileSystemResource.exists()) {
                    String fileName = fileSystemResource.getFilename();
                    Assert.notNull(fileName, "文件名不能为空");
                    helper.addAttachment(fileSystemResource.getFilename(), fileSystemResource);
                }
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送带附件的html邮件时产生错误：{}", e);
            throw new SystemException("发送附件HTML邮件失败");
        }
        log.info("给[{}]的附件邮件[{}]发送成功", to, subject);
    }

    /**
     * 发送带附件的邮件给多个人
     *
     * @param to      收件人列表
     * @param subject 邮件题目
     * @param content 邮件内容（html）
     * @param files   邮件附件（一个或多个）
     */
    @Override
    public void sendAttachmentsMail(List<String> to, String subject, String content, List<String> files) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to.toArray(String[]::new));
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            for (String file : files) {
                FileSystemResource fileSystemResource = new FileSystemResource(file);
                if (fileSystemResource.exists()) {
                    String fileName = fileSystemResource.getFilename();
                    Assert.notNull(fileName, "文件名不能为空");
                    helper.addAttachment(fileSystemResource.getFilename(), fileSystemResource);
                }
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送带附件的html邮件时产生错误：{}", e);
            throw new SystemException("发送附件HTML邮件失败");
        }
        log.info("给[{}]的附件邮件[{}]发送成功", Arrays.toString(to.toArray()), subject);
    }

    /**
     * 发送html邮件，包含多媒体替换内容
     *
     * @param to      收件人
     * @param subject 邮件题目
     * @param content 邮件内容（html）
     * @param inlines 媒体替换内容列表
     */
    @Override
    public void sendHtmlMailWithInline(String to, String subject, String content, List<ItemEntry> inlines) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            for (ItemEntry inline : inlines) {
                helper.addInline(inline.getKey(), new FileSystemResource(inline.getValue()));
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送html邮件时产生错误：{}", e);
            throw new SystemException("发送HTML邮件失败");
        }
        log.info("给[{}]的媒体邮件[{}]发送成功", to, subject);
    }

    /**
     * 发送html邮件，包含多媒体替换内容
     *
     * @param to      收件人列表
     * @param subject 邮件题目
     * @param content 邮件内容（html）
     * @param inlines 媒体替换内容列表
     */
    @Override
    public void sendHtmlMailWithInline(List<String> to, String subject, String content, List<ItemEntry> inlines) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to.toArray(String[]::new));
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            for (ItemEntry inline : inlines) {
                helper.addInline(inline.getKey(), new FileSystemResource(inline.getValue()));
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送html邮件时产生错误：{}", e);
            throw new SystemException("发送HTML邮件失败");
        }
        log.info("给[{}]的媒体邮件[{}]发送成功", to, subject);
    }

    /**
     * 发送html带附件邮件，包含多媒体替换内容
     *
     * @param to      收件人
     * @param subject 邮件题目
     * @param content 邮件内容（html）
     * @param files   附件列表
     * @param inlines 媒体替换内容列表
     */
    @Override
    public void sendAttachmentsMailWithInline(String to, String subject, String content, List<String> files, List<ItemEntry> inlines) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            for (ItemEntry inline : inlines) {
                helper.addInline(inline.getKey(), new FileSystemResource(inline.getValue()));
            }
            for (String file : files) {
                FileSystemResource fileSystemResource = new FileSystemResource(file);
                if (fileSystemResource.exists()) {
                    String fileName = fileSystemResource.getFilename();
                    Assert.notNull(fileName, "文件名不能为空");
                    helper.addAttachment(fileSystemResource.getFilename(), fileSystemResource);
                }
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送带附件的html邮件时产生错误：{}", e);
            throw new SystemException("发送附件HTML邮件失败");
        }
        log.info("给[{}]的媒体附件邮件[{}]发送成功", to, subject);
    }

    /**
     * 发送html带附件邮件，包含多媒体替换内容
     *
     * @param to      收件人列表
     * @param subject 邮件题目
     * @param content 邮件内容（html）
     * @param files   附件列表
     * @param inlines 媒体替换内容列表
     */
    @Override
    public void sendAttachmentsMailWithInline(List<String> to, String subject, String content, List<String> files, List<ItemEntry> inlines) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(to.toArray(String[]::new));
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.setFrom(this.from);
            for (ItemEntry inline : inlines) {
                helper.addInline(inline.getKey(), new FileSystemResource(inline.getValue()));
            }
            for (String file : files) {
                FileSystemResource fileSystemResource = new FileSystemResource(file);
                if (fileSystemResource.exists()) {
                    String fileName = fileSystemResource.getFilename();
                    Assert.notNull(fileName, "文件名不能为空");
                    helper.addAttachment(fileSystemResource.getFilename(), fileSystemResource);
                }
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            log.warn("发送带附件的html邮件时产生错误：{}", e);
            throw new SystemException("发送附件HTML邮件失败");
        }
        log.info("给[{}]的媒体附件邮件[{}]发送成功", to, subject);
    }

}
